package lg.minecraft.plugin.pokemonmenu.util.pokemondata.storage;

import com.cobblemon.mod.common.pokemon.Pokemon;
import lg.minecraft.plugin.pokemonmenu.LGPokemonMenu;
import net.minecraft.class_2487;
import net.minecraft.class_2507;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

/**
 * @author langle__
 * @version 1.0
 */
public class FileStorage extends PokemonDataStorage {

    private final File folder;

    public FileStorage(File folder) {
        this.folder = folder;
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                LGPokemonMenu.getInstance().getLogger().warning("Failed to create pokemon data folder.");
            } else {
                LGPokemonMenu.getInstance().getLogger().info("Pokemon data folder created.");
            }
        }
    }

    @Override
    public @Nullable Pokemon getPokemon(@NotNull UUID uuid) {
        File file = new File(folder, uuid + ".nbt");
        if (!file.exists()) return null;
        try (DataInputStream input = new DataInputStream(Files.newInputStream(file.toPath()))) {
            class_2487 nbt = class_2507.method_10627(input);
            return fromNBT(nbt);
        } catch (Exception e) {
            LGPokemonMenu.getInstance().getLogger().warning("Failed to read pokemon data from file: " + file.getAbsolutePath() + " - " + e.getMessage());
            return null;
        }
    }

    @Override
    public boolean savePokemon(@NotNull UUID uuid, @NotNull Pokemon pokemon) {
        File file = new File(folder, uuid + ".nbt");
        class_2487 nbt = toNBT(pokemon);
        try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(file.toPath()))) {
            class_2507.method_10628(nbt, output);
        } catch (IOException e) {
            LGPokemonMenu.getInstance().getLogger().warning("Failed to delete pokemon data file: " + file.getAbsolutePath());
            return false;
        }
        return true;
    }

    @Override
    public boolean removePokemon(@NotNull UUID uuid) {
        File file = new File(folder, uuid + ".nbt");
        if (file.exists()) {
            if (!file.delete()) {
                LGPokemonMenu.getInstance().getLogger().warning("Failed to delete pokemon data file: " + file.getAbsolutePath());
                return false;
            }
        }
        return true;
    }

}
